package com.lagou.bean;

import com.lagou.filter.Dimension;
import com.lagou.filter.TPMonitorFilter;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;


public class MonitorExecutor extends FixedThreadPool implements Runnable{

    protected double percent90 = 0.9;  //90分位
    protected double percent99 = 0.99; //99分位

    @Override
    public void run() {
        System.out.println("5s 执行一次");
        //执行过滤器
        HashMap<String, TreeSet<Dimension>> statistics = TPMonitorFilter.REQUEST_STATISTICS;

        //遍历hashmap
        Set<Map.Entry<String, TreeSet<Dimension>>> set = statistics.entrySet();
        for (Map.Entry<String, TreeSet<Dimension>> entry : set) {
            String service = entry.getKey();//serviceName:com.lagou.service.HelloService:methodX
            TreeSet<Dimension> value = entry.getValue();//存放的是消耗的时间和请求时间
            System.out.println("=====服务个数："+statistics.size());
            report(value, service);
        }
    }

    //读取方法请求的TP90、TP99耗时情况
    protected void report(TreeSet<Dimension> statistics, String service) {

        synchronized (statistics) {
            long startTime = System.currentTimeMillis() - 60 * 1000; //获取一分钟前的时间
            for (Dimension data : statistics) {//开始请求时间与当前时间进行对比 超过一分 视为无效请求,移除
                if (data.sendTime < startTime) {
                    statistics.remove(data);
                }
            }

            //获取集合大小
            int size = statistics.size();
            int percent90Point = (int) (size * percent90);
            int percent99Point = (int) (size * percent99);

            Dimension percent90PointData = null;
            Dimension percent99PointData = null;
            int counter = 1;
            //循环请求数据 直到请求次数等于设定的时间
            System.out.println("tresset节点个数：" + statistics.size());
            for (Dimension data : statistics) {
                if (counter == percent90Point) { //TP90
                    percent90PointData = data;
                } else if (counter == percent99Point) { // TP99
                    percent99PointData = data;
                }
                counter++;
            }

            System.out.println("=========服务请求方法"+service);
            if (percent90PointData != null) {
                System.out.println("  90分位点耗时=============" +  percent90PointData.spendTime);
            }

            if (percent99PointData != null) {
                System.out.println("  99分位点耗时=============" + percent99PointData.spendTime);
            }
        }
    }
}
